<template>
    <view class="container">
        <!-- 顶部志愿者统计数据和城市定位 -->
        <!-- <view class="header">
            <view class="header-left" @click="navigateToCitySelect">
                <text class="city">{{ currentCity }} {{ currentDistrict }}</text>
                <view class="iconfont icon-xiala location-icon"></view>
                <text class="volunteer-count">4,325,583 志愿者</text>
            </view>
            <view class="iconfont icon-sousuo search-icon"></view>
        </view> -->

        <!-- 轮播图模块 -->
        <swiper class="banner" autoplay="true" interval="3000" indicator-dots="true" circular="true">
            <swiper-item v-for="image in bannerImages" :key="image.id">
                <image :src="image.picUrl" mode="widthFix" @click="redirectUrl(image.redirectUrl)" class="banner-img" />
            </swiper-item>
        </swiper>
        <!-- 导航栏，两行布局 -->
        <view class="nav">
            <view class="nav-row">
                <view v-if="enable" class="nav-item" @click="navigateTo(item.url)"
                    v-for="(item, index) in navItems.slice(0, 2)" :key="index">
                    <view class="iconfont" :class="item.icon" :style="{ color: item.color }"></view>
                    <text class="nav-text">{{ item.text }}</text>
                </view>
            </view>
            <view class="nav-row">
                <view class="nav-item" v-if="enable" v-for="(item, index) in navItems.slice(2, 4)" :key="index"
                    @click="navigateTo(item.url)">
                    <view class="iconfont" :class="item.icon" :style="{ color: item.color }"></view>
                    <text class="nav-text">{{ item.text }}</text>
                </view>
            </view>
        </view>

        <!-- 通讯福利广告 -->
        <view class="ad" @click="partner">
            <image src="https://cdn1.sanyedu.com/static/img/hhr.jpg" mode="widthFix" class="ad-img">
            </image>
            <!-- <text class="ad-text">成为合伙人</text> -->
        </view>



        <!-- 活动时间选择 -->
        <view class="activity">
            <view class="activity-header">
                <text class="activity-title">找活动</text>
                <view class="activity-more" @click="goToActivityList">
                    <text class="more-text">查看更多</text>
                    <view class="iconfont icon-arrow-right arrow-icon"></view>
                </view>
            </view>
            <view class="date-picker">
                <view class="date" v-for="(date, index) in dates" :key="index">
                    <text :class="['date-text', { active: index === selectedDateIndex }]" @click="selectDate(index)">{{
                        date.label }}</text>
                </view>
            </view>
        </view>

        <!-- 活动列表模块 -->
        <view class="activity-list">
            <view class="activity-card" v-for="activity in activities" :key="activity.id"
                @click="goToActivityDetail(activity.id)">
                <!-- 活动图片 -->
                <image :src="activity.cover" mode="widthFix" class="activity-image"></image>

                <!-- 活动信息 -->
                <view class="activity-content">
                    <!-- 活动标题 -->
                    <view class="activity-title">{{ activity.location }}</view>

                    <!-- 活动地点 -->
                    <view class="activity-location">
                        <view class="iconfont icon-heart activity-icon"></view>
                        <view class="activity-location-text" v-html="activity.description"></view>
                    </view>

                    <!-- 活动区域和距离 -->
                    <view class="activity-distance">
                        <view class="iconfont icon-ditu activity-icon"></view>
                        <text class="activity-distance-text">{{ activity.startTime }} | {{ activity.expireTime
                            }}km</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                currentCity: "定位中...", // 默认定位城市
                currentDistrict: "", // 定位区信息
                navBarHeight: 88, // 初始默认值，可动态更新
                bannerImages: [],
                navItems: [
                    { icon: 'icon-xiaoshou',text: '农村产品',color: '#48a473',url: '/subPackage2/villageSupport/villageSupport' },
                    { icon: 'icon-wangzhantubiaoji2_huaban1fuben11',text: '担保用户',color: '#f58b47',url: '/subPackage1/marriageHelp/marriageHelp' },
                    { icon: 'icon-gongzuoshi',text: '闲置资源',color: '#1c8bfb',url: '' },
                    { icon: 'icon-juminjiankangqia-',text: '项目发布',color: '#f54394',url: '/subPackage3/list' },
                    // { icon: 'icon-gaoxiaozhuxuejin',text: '扶贫助学',color: '#ffb400',url: '' },
                    // { icon: 'icon-a-Designforeveryone',text: '惠民养老',color: '#7347f5',url: '' },
                ],
                dates: [],
                selectedDateIndex: 0,
                activities: [],
                enable: false
            };
        },
        onShow() {

            uni.getStorage({
                key: 'selectedCity',
                success: (res) => {
                    this.currentCity = res.data;
                    uni.removeStorage({ key: 'selectedCity' });
                }
            });

        },

        methods: {
            navigateToVillageSupport() {
                uni.navigateTo({
                    url: '/pagesB/detail/detail'
                });
            },
            navigateTo(url) {
                console.log(url);
                if (this.f.isnull(url) == '') {
                    this.f.msg('此功能正在开发中，敬请期待！')
                } else {
                    uni.navigateTo({
                        url: url
                    });
                }
                // 使用路径 '/subPackage1/pages/marriageHelp/marriageHelp' 跳转到分包页面

            },
            // 跳转到活动详情页面
            goToActivityDetail(id) {
                uni.navigateTo({
                    url: `/pages/ActivityDetail/ActivityDetail?id=${id}`
                });
            },
            // 跳转到活动列表页面
            goToActivityList() {
                console.log('点击查看更多按钮');
                uni.navigateTo({
                    url: '/pages/ActivityList/ActivityList',
                    success: () => {
                        console.log('跳转成功');
                    },
                    fail: (err) => {
                        console.error('跳转失败:', err);
                        uni.showToast({
                            title: '页面不存在',
                            icon: 'none'
                        });
                    }
                });
            },
            // 跳转到城市选择页面
            navigateToCitySelect() {
                uni.navigateTo({
                    url: '/pages/citySelect/citySelect' // 假设页面路径为 /pages/citySelect/citySelect
                });
            },
            // 计算并设置导航栏高度
            calculateNavBarHeight() {
                const systemInfo = uni.getSystemInfoSync();
                const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
                const navHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
                this.navBarHeight = navHeight;
            },
            // 自动定位功能
            getLocation() {
                uni.getLocation({
                    type: 'gcj02',
                    success: (location) => {
                        const { latitude,longitude } = location;
                        this.reverseGeocode(latitude,longitude); // 反向地理编码获取城市信息
                    },
                    fail: () => {
                        this.currentCity = "定位失败";
                    }
                });
            },
            // 反向地理编码获取城市和区
            reverseGeocode(lat,lng) {
                uni.request({
                    url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=3LQBZ-JOZ3F-QVRJY-JQCQQ-6NHNS-A7BBV`, // 替换为您的腾讯地图API Key
                    success: (res) => {
                        if (res.data.status === 0) {
                            const { city } = res.data.result.address_component;
                            this.currentCity = city || "未知城市";
                            this.f.storage('address',city)
                            this.currentDistrict = district || "";
                        } else {
                            this.currentCity = "定位失败";
                        }
                    },
                    fail: () => {
                        this.currentCity = "定位失败";
                    }
                });
            },
            // 获取日期
            getDates() {
                const dayNames = ['周日','周一','周二','周三','周四','周五','周六'];
                const currentDate = new Date();
                const dateArray = [];

                for (let i = 0; i < 7; i++) {
                    const date = new Date(currentDate);
                    date.setDate(currentDate.getDate() + i);

                    const dayLabel = i === 0 ? '今天' : dayNames[date.getDay()];
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    const formattedDate = `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
                    const fullDate = `${date.getFullYear()}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;

                    dateArray.push({
                        label: `${dayLabel}\n${formattedDate}`,
                        date: formattedDate,
                        fullDate: fullDate // 添加完整的年月日字段
                    });
                }
                this.dates = dateArray;
            },


            selectDate(index) {
                this.selectedDateIndex = index;
                this.getActivityScheduled()
            },

            // 合伙人页面跳转
            partner() {
                uni.navigateTo({
                    url: '/pages/member/member'
                })
            },

            // 获取轮播图
            getBannerImages() {
                this.$api.req('/station/ads/list',{
                    stationId: 0
                },'get','JSON',false).then(res => {
                    console.log(res);

                    this.bannerImages = res.data
                })
            },

            // 轮播图跳转链接
            redirectUrl(url) {
                console.log(url)
                this.f.nav(url)
            },

            // 获取活动列表
            // getActivityList(){
            // 	this.$api.req('/station/activity/list', false).then(res => {
            // 		this.activities = res.data
            // 		this.activities.forEach(item=>{
            // 			item.startTime=this.f.formatTimestamp(item.startTime,'yyyy-MM-dd')
            // 			item.expireTime=this.f.formatTimestamp(item.expireTime,'yyyy-MM-dd')
            // 		})
            // 	})
            // },

            // 活动日期筛选-列表
            getActivityScheduled() {
                var t = this
                t.$api.req('/station/activity/scheduled',{
                    dates: t.dates[t.selectedDateIndex].fullDate
                },"get","JSON",false).then(res => {
                    // this.activities可能为空，需要判断
                    this.activities = res.data || []
                    this.activities.forEach(item => {
                        item.startTime = this.f.formatTimestamp(item.startTime,'yyyy-MM-dd hh:mm:ss')
                        item.expireTime = this.f.formatTimestamp(item.expireTime,'yyyy-MM-dd hh:mm:ss')
                    })
                })
            },
        },
        mounted() {
            const switchCfg = this.f.storage('switchCfg');
            this.enable = switchCfg && switchCfg.module ? switchCfg.module.enable : false;
            console.log(this.enable);
            // this.calculateNavBarHeight();  

            this.getDates();
            // this.getLocation();
            this.getBannerImages();
            // this.getActivityList();
            this.getActivityScheduled()
        }
    }
</script>

<style>
    .container {
        /* background-color: #f2f2f2; */
        padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
        padding-left: 20rpx;
        padding-right: 20rpx;
    }

    /* 顶部头部排版 */
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10rpx 0;
    }

    .header-left {
        display: flex;
        align-items: center;
        cursor: pointer;
    }

    .city {
        font-size: 36rpx;
        font-weight: bold;
    }

    .location-icon {
        font-size: 22rpx !important;
        color: #666;
        margin-left: 5rpx;
    }

    .volunteer-count {
        font-size: 26rpx;
        color: #666;
        margin-left: 10rpx;
    }

    /* 搜索图标样式 */
    .search-icon {
        font-size: 40rpx;
        color: #333;
    }

    /* 轮播图模块 */
    .banner {
        margin-top: 20rpx;
        height: 400rpx;
    }

    .banner-img {
        width: 100%;
        height: 400rpx;
    }

    /* 导航栏样式 */
    .nav {
        margin-top: 30rpx;
    }

    .nav-row {
        display: flex;
        justify-content: space-around;
        margin-bottom: 20rpx;
    }

    .nav-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 25%;
    }

    .iconfont {
        font-size: 60rpx;
    }

    .nav-text {
        margin-top: 10rpx;
        font-size: 24rpx;
        text-align: center;
    }

    .ad {
        position: relative;
        /* 设置相对定位，为了让子元素绝对定位 */
        margin-top: 30rpx;
    }

    .ad-img {
        width: 100%;
        display: block;
    }

    .ad-text {
        position: absolute;
        top: 50%;
        /* 垂直居中 */
        left: 50%;
        /* 水平居中 */
        transform: translate(-50%, -50%);
        /* 调整偏移，使文本准确居中 */
        font-size: 48rpx;
        /* 更大的字体大小 */
        color: #ffffff;
        /* 白色文字 */
        font-weight: bold;
        text-align: center;
        background-color: rgba(0, 0, 0, 0.6);
        /* 半透明黑色背景 */
        padding: 20rpx 40rpx;
        /* 增加内边距，确保标题更大 */
        border-radius: 30rpx;
        /* 更大的圆角效果 */
        letter-spacing: 2rpx;
        /* 增加字间距，使文字看起来更有层次 */
    }



    /* 活动时间选择 */
    .activity {
        margin-top: 40rpx;
    }

    .activity-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20rpx;
    }

    .activity-title {
        font-size: 32rpx;
        font-weight: bold;
    }

    .activity-more {
        display: flex;
        align-items: center;
    }

    .more-text {
        font-size: 26rpx;
        color: #666;
        margin-right: 5rpx;
    }

    .arrow-icon {
        font-size: 26rpx;
        color: #666;
    }

    .date-picker {
        display: flex;
        justify-content: space-around;
        margin-top: 20rpx;
    }

    .date {
        text-align: center;
    }

    .date-text {
        font-size: 26rpx;
        color: #333;
    }

    .date-text.active {
        color: #00aaff;
        font-weight: bold;
    }

    .activity-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        margin-top: 20rpx;
    }

    .activity-card {
        width: 48%;
        background-color: #fff;
        border-radius: 12rpx;
        overflow: hidden;
        margin-bottom: 20rpx;
        box-shadow: 0 5rpx 10rpx rgba(0, 0, 0, 0.1);
    }

    .activity-image {
        width: 100%;
        height: 300rpx !important;
        object-fit: cover;
    }

    .activity-content {
        padding: 15rpx;
    }

    .activity-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
    }

    .activity-location {
        display: flex;
        align-items: center;
        margin-bottom: 5rpx;
    }

    .activity-location-text {
        font-size: 24rpx;
        color: #666;
        margin-left: 8rpx;
    }

    .activity-distance {
        display: flex;
        align-items: center;
    }

    .activity-distance-text {
        font-size: 24rpx;
        color: #999;
        margin-left: 8rpx;
    }

    .activity-icon {
        font-size: 24rpx;
        color: #f85858;
    }
</style>